package com.cjb.cloudmqtt.mqtt.subscribe;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.cjb.cloudmqtt.mqtt.entity.DeviceStatus;
import com.cjb.common.common.cache.RedisCache;
import com.cjb.common.util.ChangeTypeUtil;
import com.cjb.common.util.Common;
import com.cjb.common.util.JsonUtils;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
@AllArgsConstructor
public class MqttConsumerCallBack implements MqttCallback {
    /**
     * 注入redis类
     */
    private final  RedisCache redisCache;

    /*半小时过期*/
    public final static long DEFAULT_EXPIRE = 60 * 30 * 1L;
    /**
     * 客户端断开连接的回调
     */
    @SneakyThrows
    @Override
    public void connectionLost(Throwable throwable) {
        log.error("与服务器断开连接，可重连");
        log.error(String.valueOf(throwable));
    }


    /**
     * 消息到达的回调
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) {
        System.out.println(String.format("接收消息主题 : %s", topic));
        System.out.println(String.format("接收消息Qos : %d", message.getQos()));
        System.out.println(String.format("接收消息内容 : %s", new String(message.getPayload())));
        System.out.println(String.format("接收消息retained : %b", message.isRetained()));
        if (Common.isNotNull(redisCache) && Common.isNotEmpty(message.getPayload())) {
            redisCache.hSet("message", "deviceStatus",new String(message.getPayload()),DEFAULT_EXPIRE);
        }
    }

    /**
     * 消息发布成功的回调
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        log.info("消息成功");
    }

}

